<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');

need_partner();

$partner_id = abs(intval($_SESSION['partner_id']));
$login_partner = Table::Fetch('partner', $partner_id);

$t_con = array(
	'partner_id' => $partner_id,
);
$teams = DB::LimitQuery('team', array('condition'=>$t_con));
$t_id = Utility::GetColumn($teams, 'id');


$condition = array(
	'team_id' => $t_id,
	'team_id > 0',
);
/* filter */
$uemail = strval($_GET['uemail']);
if ($uemail) {
	$field = strpos($uemail, '@') ? 'email' : 'username';
	//$field = is_numeric($uemail) ? 'id' : $field;
	$uuser = Table::Fetch('user', $uemail, $field);
	if($uuser) $condition['user_id'] = $uuser['id'];
	else $uemail = null;
}
$id = abs(intval($_GET['id'])); if ($id) $condition['id'] = $id;
$team_id = abs(intval($_GET['team_id']));
if ($team_id && in_array($team_id, $t_id)) {
	$condition['team_id'] = $team_id;
} else { $team_id = null; }

$cbday = strval($_GET['cbday']);
$ceday = strval($_GET['ceday']);
$pbday = strval($_GET['pbday']);
$peday = strval($_GET['peday']);
if ($cbday) { 
	$cbtime = strtotime($cbday);
	$condition[] = "create_time >= '{$cbtime}'";
}
if ($ceday) { 
	$cetime = strtotime($ceday);
	$condition[] = "create_time <= '{$cetime}'";
}
if ($pbday) { 
	$pbtime = strtotime($pbday);
	$condition[] = "pay_time >= '{$pbtime}'";
}
if ($peday) { 
	$petime = strtotime($peday);
	$condition[] = "pay_time <= '{$petime}'";
}
/* end fiter */

$count = Table::Count('order', $condition);
list($pagesize, $offset, $pagestring) = pagestring($count, 20);

$orders = DB::LimitQuery('order', array(
	'condition' => $condition,
	
	'order' => 'ORDER BY id DESC',
	'size' => $pagesize,
	'offset' => $offset,
));

foreach($orders as $key =>$val)
{
	if($val['is_pin'] == 1)
	{
		//pin_order_list
		$pin_order_list = DB::LimitQuery('pin_order_list', array(
			'condition' => array('order_id'=>$val['id']),
			'one' => true,
		));
		$pin_order =  DB::LimitQuery('pin_order', array(
			'condition' => array('id'=>$pin_order_list['pin_id']),
			'one' => true,
		));
		$val['pin_info'] = $pin_order;
		$orders[$key] = $val;
	}
}

$pay_ids = Utility::GetColumn($orders, 'pay_id');
$pays = Table::Fetch('pay', $pay_ids);

$user_ids = Utility::GetColumn($orders, 'user_id');
$users = Table::Fetch('user', $user_ids);

$team_ids = Utility::GetColumn($orders, 'team_id');
$teams = Table::Fetch('team', $team_ids);

include template('biz_order');
